package com.jprocms.module.cms.service.email;

import com.jprocms.module.cms.api.dto.EmailConfig;
import com.jprocms.module.cms.service.globalconfig.GlobalConfigService;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Properties;


@Component
public class EmailService {

    private GlobalConfigService globalConfigService;

    public EmailService(GlobalConfigService globalConfigService) {
        this.globalConfigService = globalConfigService;
    }

    public void sendMail(String[] to, String subject, String text) {
        EmailConfig emailConfig = globalConfigService.getDefGlobalConfig().getEmailConfig();
        if (emailConfig.getHost() == null) {
            throw new RuntimeException("Email SMTP host is not set");
        }
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost(emailConfig.getHost());
        mailSender.setUsername(emailConfig.getUsername());
        mailSender.setPassword(emailConfig.getPassword());
        mailSender.setDefaultEncoding("UTF-8");
        mailSender.setPort(emailConfig.getPort() != null ? emailConfig.getPort() : 465);

        Properties prop = new Properties();
        prop.setProperty("mail.smtp.auth", "true");
        if (emailConfig.isSsl()) {
            prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        }
        if (emailConfig.getTimeout() != null) {
            prop.setProperty("mail.smtp.timeout", emailConfig.getTimeout().toString());
        }
        mailSender.setJavaMailProperties(prop);
        MimeMessage msg = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(msg, true, "UTF-8");
            helper.setFrom(emailConfig.getFrom());
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(text, false);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
        mailSender.send(msg);
    }
}
